<?php
/**
 * 网站会话管理
 * @author yagas<yagas@sohu.com>
 * @version 2.0
 */
class CscSession extends CHttpSession {
	const CACHE_KEY_PREFIX = 'Yii.CscSession.';
	
	public $cacheID  = 'cache';
	public $service;
	public $memcache = false;
	protected $hessian;
	private $_cache;
	
	public function init() {
	    ini_set( 'session.name', 'sessionId' );
	    ini_set( 'session.cookie_domain', '.'.DOMAIN );

	    if ( $this->memcache ) {
	        $this->_cache=Yii::app()->getComponent( $this->cacheID );
	        if( !($this->_cache instanceof ICache) )
	            throw new CException(Yii::t('yii','CCacheHttpSession.cacheID is invalid. Please make sure "{id}" refers to a valid cache application component.',
	                    array('{id}'=>$this->cacheID)));
	    }
		
		parent::init();
	}
	
	/**
	 * 是否自定义会话读写过程
	 * @see CHttpSession::getUseCustomStorage()
	 */
	public function getUseCustomStorage() {
	    return $this->memcache;
	}	
	
	/**
	 * 开启session
	 * @see CHttpSession::open()
	 */
	public function open() {
		//读取sessionId
		$cookie    = Yii::app()->request->cookies['sessionId'];
		$sessionID = is_null($cookie)?uuid() : $cookie->value;
		$this->setSessionID( $sessionID );
		parent::open();
	}

	/**
	 * 读取session变量值
	 * @see CHttpSession::get()
	 * @param string $key          session变量名
	 * @param mixed  $defaultValue 默认值，当无法取得数据时，返回本设置值
	 * @return mixed
	 */
	public function get( $key, $defaultValue=null ) {	   
		    return parent::get( $key, $defaultValue );

	}

	/**
	 * 设置session变量值
	 * @see CHttpSession::add()
	 * @param string $key          session变量名
	 * @param mixed  $value 
	 * @return mixed
	 */
	public function add( $key, $value ) {
		    parent::add( $key, $value );
	}
	
	/**
	 * 删除session变量
	 * @see CHttpSession::remove()
	 * @param string $key session变量名
	 */
	public function remove($key) {
		return parent::remove( $key );
	}
	
	/**
	 * 重设sessionID
	 * @param string $sessionID
	 */
	public function changeSessionID( $sessionID ) {
		$tmp = $this->toArray();
		$this->destroy();
		
		$this->setSessionID( $sessionID );
		
		//设置sessionId
		$cookie           = new CHttpCookie( "sessionId", $sessionID );
		$cookie->domain   = DOMAIN;
		Yii::app()->request->cookies["sessionId"] = $cookie;
		
		$this->open();

		//reset
		if ( $tmp ) {
			foreach( $tmp as $key => $value ) {
				$this->add($key, $value);
			}
		}
	}
	
	public function readSession($id) {	    
	    $data=$this->_cache->get($this->calculateKey($id));
	    return $data===false?'':$data;
	}
	
	public function writeSession($id,$data) {
	    return $this->_cache->set($this->calculateKey($id),$data,$this->getTimeout());
	}
	
	public function destroySession($id) {
	   return $this->_cache->delete($this->calculateKey($id));
	}
	
    protected function calculateKey($id) {
	    return self::CACHE_KEY_PREFIX.$id;
	}
}